/*
 * Copyright 2008-2023 dexian.vip. All rights reserved.
 * Support: http://www.dexian.vip
 * License: http://www.dexian.vip/license
 */

package vip.dexian.core.security;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.util.Assert;

import java.io.Serial;
import java.util.List;

/**
 * 自定义授权权限模式。 Perms表示为： admin:list -> /admin/list
 *
 * @author 挺好的 2023年06月05日 15:52
 */
public class PermsGrantedAuthority implements GrantedAuthority {

    @Serial
    private static final long serialVersionUID = 8339088195028051526L;

    /**
     * 角色。保留角色，主要是为了应对以角色方式的授权校验。
     */
    private String role;

    /**
     * 权限
     */
    private List <String> authorities;

    public PermsGrantedAuthority () {
    }

    public PermsGrantedAuthority (String role) {
        Assert.hasText(role, "A granted authority textual representation is required");
        this.role = role;
    }

    public PermsGrantedAuthority (String role, List <String> authorities) {
        this(role);
        this.authorities = authorities;
    }

    /**
     * 获取角色
     *
     * @return 角色标识
     */
    @Override
    public String getAuthority () {
        return this.role;
    }

    /**
     * 获取权限列表
     *
     * @return 权限列表，有可能为空集合
     */
    public List <String> getAuthorities () {
        return this.authorities;
    }

    @Override
    public boolean equals (Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj instanceof PermsGrantedAuthority permsGrantedAuthority) {
            return this.role.equals(permsGrantedAuthority.role);
        }
        return false;
    }

    @Override
    public int hashCode () {
        return this.role.hashCode();
    }

    @Override
    public String toString () {
        return this.role;
    }
}
